# encoding:utf-8
"""
@author: quanjie
@contact:
@time: 2022/1/8 11:51
"""
import logging

import chardet
import requests
import urllib3


class BaseRequests(object):
    def __init__(self, *args, **kwargs):
        super().__init__()
        self.response = None

    def get(self, url, params=None, encoding=None, **kwargs):
        """
            GET请求方法
            :param url: 抓取的url
            :param encoding: 解码文本的字符编码
            :param params: 需要传输的数据
        """
        if not kwargs.get('headers', None):
            kwargs['headers'] = {
                'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20120101 Firefox/33.0"}
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
        self.response = requests.get(url=url, params=params, **kwargs)
        return self.response.status_code,self.custom_charset(charset=encoding)

    def post(self, url, data, encoding=None, json=None, **kwargs):
        """
            POST请求方法
            :param url: 抓取的url
            :param data: 需要传输的数据
            :param encoding: 解码文本的字符编码
            :param json: 请求需要传输的json文本
        """
        if not kwargs.get('headers', None):
            kwargs['headers'] = {'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20120101 Firefox/33.0"}

        self.response = requests.post(url, data=data, json=json, **kwargs)
        return self.response.status_code,self.custom_charset(charset=encoding)

    def custom_charset(self, charset=None):
        """
            通过自定义网页编码格式获取网页内容
            :param charset: None 自己指定的charset，不指定会自动检测
        """
        if not chardet:
            self.response.encoding = chardet.detect(self.response.content)
        else:
            self.response.encoding = charset
        return self.response.text

    def get_cookies(self):
        """
            获取cookies
        """
        if "response" not in vars(self) or not self.response:
            return None
        return self.response.cookies
